package com.hrhr74.penguinstream.utils;

import cn.hutool.core.util.RandomUtil;
import com.hrhr74.penguinstream.constant.UserConstant;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
public class CodeUtil {
    private static final Logger log = LoggerFactory.getLogger(CodeUtil.class);
    public final StringRedisTemplate stringRedisTemplate;

    /**
     * 创建并获取一个验证码
     * @param phone
     * @return
     */
    public String createCode(String phone){
        String key = UserConstant.CODE_KEY + phone;
        //检查redis中是否有验证码
        String redisCode = stringRedisTemplate.opsForValue().get(key);
        if(redisCode != null && !redisCode.isEmpty()){
            return redisCode;
        }

        String code = RandomUtil.randomNumbers(UserConstant.CODE_LENGTH);

        //将code写入redis
        stringRedisTemplate.opsForValue().set(key, code,UserConstant.CODE_TTL, TimeUnit.SECONDS);

        return code;
    }


    /**
     * 检验验证码
     * @param phone
     * @param code
     * @return
     */
    public boolean checkCode(String phone,String code){
        String key = UserConstant.CODE_KEY + phone;
        String redisCode = stringRedisTemplate.opsForValue().get(key);
        if(redisCode == null || redisCode.isEmpty()){
            return false;
        }

        if(!redisCode.equals(code)){
            return false;
        }
        //验证成功后将验证码删除以防止二次使用
        stringRedisTemplate.delete(key);
        return true;
    }
}
